package net.atomarrow.controllers.converter;

import java.util.ArrayList;
import java.util.List;

public class TypeConverter {

    private List<IConverter> converters;

    public TypeConverter(){
        converters=new ArrayList<IConverter>();
        converters.add(new StringConverter());
        converters.add(new IntegerConverter());
        converters.add(new DoubleConverter());
        converters.add(new DateConverter());
        converters.add(new TimeConverter());
        converters.add(new FloatConverter());
        converters.add(new LongConverter());
        converters.add(new BooleanConverter());
        converters.add(new ArrayConverter());
        converters.add(new ListConverter());
        converters.add(new EnumConverter());
    }

    public <T>T converter(Object[] values,Class<T> clazz) throws TypeMismatchException{
        if(clazz==Object.class){
            if(values==null||values.length==0){
                return null;
            }
            Object value =values[0];
            if(value==null){
                return null;
            }
            return (T) value;
        }
        for(IConverter converter:converters){
            if(converter.canHandle(clazz)){
            	try{
            		return converter.converter(values, clazz);
            	}catch (Exception e) {
					break;
				}
            }
        }
        throw new TypeMismatchException(clazz.getName()+" can not be convert");
    }

}
